/***************************************************************************
 *   Copyright 2010 long2015 liu <long2015@gmail.com>
 *
 *   This program is free software; you can redistribute it and/or
 *   modify it under the terms of the GNU General Public
 *   License as published by the Free Software Foundation; either
 *   version 2 of the License, or (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 ***************************************************************************/
//md 怪了
#include<QtGui>
#include "jigsaw.h"
#include<QVariant>
#include<QMessageBox>
#include<QtGlobal>
#include<time.h>
//test eclipse + qtsdk + git
Jigsaw::Jigsaw(QWidget *)
{

    QTextCodec::setCodecForTr(QTextCodec::codecForName("utf8"));
    //构建界面
    resize(640,480);
    label1 = new QLabel(tr("拼图程序"),this);
    label1->setFrameStyle(QFrame::Panel | QFrame::Sunken);
    label1->setGeometry(500,0,100,50);
    label2 = new QLabel(tr("A Step:"),this);
    label2->setGeometry(500,140,100,380);
    label2->setFrameStyle(QFrame::Panel | QFrame::Sunken);
    label2->setAlignment(Qt::AlignTop | Qt::AlignLeft);
    fileButton = new QPushButton(tr("加载新图片"),this);
    fileButton->setGeometry(500,60,100,30);
    fileButton->setDefault(false);
    connect(fileButton,SIGNAL(clicked()),this,SLOT(open()));
    disorderButton = new QPushButton(tr("重新开始"),this);
    disorderButton->setGeometry(500,100,100,30);
    connect(disorderButton,SIGNAL(clicked()),this,SLOT(disorder()));

    //图片背景
    //img=QPixmap(480,480);
    QPainter pp(&img);
    pp.setBrush(QBrush(Qt::gray,Qt::SolidPattern));
    pp.drawRect(0,0,480,480);

    img=QPixmap(":/image/android.jpeg");
    makeImg();
}

void Jigsaw:: makeImg()
{
    //
    QPainter p(&img);
    p.drawPixmap(0,0,480,480,img);
    //图像分块存储（到image[9]数组）
    if(!img.isNull())
    {
        for(int i=0; i<8; i++)
        {
            image[i]=img.copy((i%3)*160,(i/3)*160,160,160);
        }
        image[8]=QPixmap();
    }
    else
    {
        QMessageBox::information(this,"Select again",
                                 tr("抱歉！\n加载图片中遇到错误错误.\n可能图片太小或则您的图片格式暂不支持.\n请重新选择"));
    }
    //各方块的起点坐标
    for(int i=0; i<9; i++)
    {

        point[i]=QPoint((i%3)*161,(i/3)*161);
    }
    disorder();
}
void Jigsaw::disorder()
{
    //回复原始
    for(int i=0; i<9; i++) n[i]=i;
    blank=8;
    for(int i=0; i<8; i++)
    {
        image[i]=img.copy((i%3)*160,(i/3)*160,160,160);
    }

    image[8]=QPixmap();
    //再乱序
    qsrand(time(NULL));
    int temp=rand();
    int a[8];
    for(int i=0; i<8; i++)
    {
        a[i]=temp%10%8;
        temp/=10;
    }
    for(int i=0; i<8; i++)
    {
        temp=n[a[i]];
        n[a[i]]=n[i];
        n[i]=temp;
    }
    update();
}

void Jigsaw::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    for(int i=0; i<9; i++)
    {
        painter.drawPixmap(point[i].x(),point[i].y(),160,160,image[n[i]]);
    }
}

void Jigsaw::keyReleaseEvent(QKeyEvent *event)
{
    int ablank = blank%3;
    int bblank = blank/3;
    int exchange;
    if(event->key()==Qt::Key_Down)
    {
        if(bblank > 0) //不再顶端
        {
            exchange=bblank*3+ablank-3;
            exchangePoint(exchange);
            setText(blank);
            update();
        }
    }
    else if(event->key()==Qt::Key_Up)
    {
        if(bblank < 2) //不再底部
        {
            exchange=bblank*3+ablank+3;
            exchangePoint(exchange);
            setText(blank);
            update();
        }
    }
    else if(event->key()==Qt::Key_Left)
    {
        if(ablank < 2) //不再右端
        {
            exchange=bblank*3+ablank+1;
            exchangePoint(exchange);
            setText(blank);
            update();
        }
    }
    else if(event->key()==Qt::Key_Right)
    {
        if(ablank > 0) //不再左端
        {
            exchange=bblank*3+ablank-1;
            exchangePoint(exchange);
            setText(blank);
            update();
        }
    }
    else //其他按键不反应
        update();
    if(isSucceed()==true)
    {
        label2->setText("OK");
        QMessageBox::information(this,"congratulation.",tr("恭喜完成.\n"));
    }
}

void Jigsaw::exchangePoint(int i)
{
    int temp=n[i];
    n[i]=8;
    n[blank]=temp;
    blank=i;
}

void Jigsaw::open()
{
    QString oldFile = fileName;
    fileName = QFileDialog::getOpenFileName(this,QString(),tr("/home/long2015"));
    img=QPixmap(fileName);
    if(!img.isNull())
    {
        makeImg();
        update();
    }
    else
    {
        fileName = oldFile;
        QMessageBox::information(this,"Select again",
                                 tr("抱歉！\n加载图片中遇到错误错误.\n可能格式错误.\n请重新选择"));
    }
}

bool Jigsaw::isSucceed()
{
    for(int i=0; i<9; i++)
        if(n[i]!=i) return false;
    return true;
}

void Jigsaw::setText(int i)
{
    int a=i%3;
    int b=i/3;
    int ex=b*3+a;
    label2->setText(QVariant(b).toString()
                    +","
                    +QVariant(a).toString()
                    +"\nblank="
                    +QVariant(ex).toString()
                    +"\n("
                    +QVariant(a*161).toString()
                    +","
                    +QVariant(b*161).toString()
                    +")");
}
